package com.example.win.android_banduyujia.venuesactivity.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.win.android_banduyujia.R;
import com.example.win.android_banduyujia.entity.Constants;
import com.example.win.android_banduyujia.lib.util.FileUtils;
import com.example.win.android_banduyujia.peopleactivity.activity.activity.openactivity.DataActivity.TeachingscopeActivity;
import com.example.win.android_banduyujia.peopleactivity.ui.activity.BaseTitleBarActivity;
import com.example.win.android_banduyujia.ui.flowLayout.FlowLayout;
import com.example.win.android_banduyujia.ui.view.CircleImageView;
import com.example.win.android_banduyujia.ui.view.ImageLoader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by Win on 2015/8/14.
 */
public class VenuesDataActivity extends BaseTitleBarActivity implements View.OnClickListener {
   public static final String TAG = VenuesDataActivity.class.getSimpleName();

    private CircleImageView  mHeaderImageView;
    private LinearLayout  mLayoutPicture, mLayoutname,mLayoutaddress;
    private TextView      mTxtname, mTxtAddress, mTxtScope;

    private FlowLayout  tag_vessel;
    private ImageView   textViewadd;
    private List<String> mTagList = new ArrayList<String>();
    private int  screenWidth = 0;
    private View   v;
    private String   mImageName = " ";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.title_venues_info);

        screenWidth = getWindowManager().getDefaultDisplay().getWidth(); // 屏幕宽（像素

        InitTitles();
        InitViews();
    }

    private void InitTitles() {
        setTitle(R.string.title_text_view_basic_data);
        showLeftBackButton();
    }

    private void InitViews() {
        mHeaderImageView = (CircleImageView) findViewById(R.id.title_photo_circle_image_venues_view);
        mTxtname = (TextView) findViewById(R.id.title_list_item_name);
        mTxtAddress = (TextView) findViewById(R.id.title_list_item_venues);
        mTxtScope= (TextView) findViewById(R.id.title_list_item_scope);

        tag_vessel = (FlowLayout)findViewById(R.id.add_tag);

        mTxtname.setOnClickListener(this);
        mTxtAddress.setOnClickListener(this);
        mTxtScope.setOnClickListener(this);

        mHeaderImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new PopupWindows(VenuesDataActivity.this, mHeaderImageView);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.title_list_item_name: // 馆名
                 VenuesNameActivity();
                break;
            case R.id.title_list_item_venues:// 馆址
                VenuesAddressActivity();
                break;
            case R.id.title_list_item_scope:// 授课范围
                VenuesScopeActivity();
                break;
        }
    }

    /**
     * 添加标签的对话框
     */
    private void VenuesNameActivity() {
      //  startActivity(new Intent(this, VenuesNameActivity.class));

        final Dialog  dlg = new Dialog(VenuesDataActivity.this, R.style.add_dialog);
        dlg.show();
        dlg.getWindow().setGravity(Gravity.CENTER);
        dlg.getWindow().setLayout((int) (screenWidth * 0.8), WindowManager.LayoutParams.WRAP_CONTENT);
        dlg.getWindow().setContentView(R.layout.view_settings_add_tags_dialog);
        TextView add_tag_dialog_title = (TextView) dlg.findViewById(R.id.text_view_add_tag_dialog_title);
        final EditText add_tag_dialog_content=(EditText)dlg.findViewById(R.id.add_tag_dialog_content);
        TextView add_tag_dialog_no = (TextView) dlg.findViewById(R.id.add_tag_dialog_no);
        TextView add_tag_dialog_ok = (TextView) dlg.findViewById(R.id.add_tag_dialog_ok);
        add_tag_dialog_title.setText("添加场馆");
        add_tag_dialog_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dlg.dismiss();
            }
        });
        add_tag_dialog_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) VenuesDataActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_NOT_ALWAYS);

                mTagList.add(add_tag_dialog_content.getText().toString());
                AddTag(mTagList.get(mTagList.size()-1), mTagList.size()-1);
                Log.v("==", mTagList.toString() + "*");
                dlg.dismiss();
            }
        });
    }

    /**
     * 添加标签
     * @param tag
     * @param i
     */
    private void AddTag(String tag, int i) {
        final TextView mTag = new TextView(VenuesDataActivity.this);
        mTag.setText(" " + tag + " ");
        mTag.setGravity(Gravity.CENTER);
        mTag.setTextSize(14);
       // mTag.setBackground(getResources().getDrawable(R.mipmap.mylable));
        mTag.setTextColor(Color.GRAY);
        LinearLayout.LayoutParams  params=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 50);
        params.setMargins(0, 10, 20, 10);
        tag_vessel.addView(mTag, params);
       // tag_vessel.addView(mTag, i, params);
        mTag.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                // 长按标签删除操作
                final AlertDialog dlg = new AlertDialog.Builder(VenuesDataActivity.this).create();
                dlg.show();
                dlg.getWindow().setGravity(Gravity.CENTER);
                dlg.getWindow().setLayout((int) (screenWidth * 0.8), WindowManager.LayoutParams.WRAP_CONTENT);
                dlg.getWindow().setContentView(R.layout.view_settings_add_tags_dialog);
                TextView add_tag_dialog_title = (TextView) dlg.findViewById(R.id.text_view_add_tag_dialog_title);
                final EditText add_tag_dialog_content = (EditText) dlg.findViewById(R.id.add_tag_dialog_content);
                TextView add_tag_dialog_no = (TextView) dlg.findViewById(R.id.add_tag_dialog_no);
                final TextView add_tag_dialog_ok = (TextView) dlg.findViewById(R.id.add_tag_dialog_ok);
                add_tag_dialog_title.setText("场馆删除确认");
                add_tag_dialog_content.setText("您确定要删除" + mTag.getText().toString() + "这个馆名吗?");
                add_tag_dialog_no.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dlg.dismiss();
                    }
                });
                add_tag_dialog_ok.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tag_vessel.removeView(mTag);
                        for (int j = 0; j < mTagList.size(); j++) {
                            Log.v("==", mTag.getText().toString() + "==" + mTagList.get(j).toString());
                            if (mTag.getText().toString().replaceAll(" ", " ").equals(mTagList.get(j).toString().replaceAll(" ", " "))) {
                                mTagList.remove(j);
                            }
                        }
                        dlg.dismiss();
                    }
                });
                return true;
            }
        });
    }

    private void VenuesAddressActivity() {
        startActivity(new Intent(this, VenuesAddressActivity.class));
    }

    private void VenuesScopeActivity() {
        startActivity(new Intent(this, TeachingscopeActivity.class));
    }

    public class PopupWindows extends PopupWindow{

        public PopupWindows(Context mContext, View parent) {
            View view = View.inflate(mContext,R.layout.title_pic_item,null);
            view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_ins));
            LinearLayout ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
            ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.push_bottom_in_2));

            setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            setBackgroundDrawable(new BitmapDrawable());
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();

            Button bt1 = (Button) view.findViewById(R.id.item_popupwindows_camera);
            Button bt2 = (Button) view.findViewById(R.id.item_popupwindows_Photo);
            Button bt3 = (Button) view.findViewById(R.id.item_popupwindows_cancel);
            bt1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    photo();
                    dismiss();
                }
            });
            bt2.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    picture();
                    dismiss();
                }
            });
            bt3.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    dismiss();
                }
            });
          }
        }

    private static final int TAKE_PICTURE = 0x000000;
    private static final int TAKE_PHOTO = 0x000001;
    private static final int TAKE_CROP = 0x000002;
    //private String path = "";

    @Override
    public void onConfigurationChanged(Configuration config) {
        super.onConfigurationChanged(config);
    }

    public void photo() {
        String  status = Environment.getExternalStorageState();
        if(status.equals(Environment.MEDIA_MOUNTED)){
            File dir = new File(Environment.getExternalStorageDirectory() + "/image/");
            if(!dir.exists())dir.mkdirs();

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            // 下面这句指定调用相机拍照后的照片存储的路径
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), ".jpg")));
           /* File file = new File(dir, String.valueOf(System.currentTimeMillis()) + ".jpg");
            path = file.getPath();
            Uri  imageUri = Uri.fromFile(file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);*/
            intent.putExtra("return-data", true);
          //  intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
            startActivityForResult(intent, TAKE_PICTURE);
        }else{
            Toast.makeText(getApplicationContext(), "没有卡", Toast.LENGTH_LONG).show();
        }
     }

    public void picture() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
       // intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, TAKE_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PHOTO: // 如果是直接从相册获取
                startPhotoZoom(data.getData());
                break;
            case TAKE_PICTURE: // 如果是调用相机拍照时
                File temp = new File(Environment.getExternalStorageDirectory() + "/.jpg");
                startPhotoZoom(Uri.fromFile(temp));
                break;
            case TAKE_CROP: // 取得裁剪后的图片
                if (data != null) {
                    setPicToView(data);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    // 裁剪图片方法实现 173 * 174
    public void startPhotoZoom(Uri uri) {
        Intent intent=new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
       // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, TAKE_CROP);
    }
    //	保存裁剪之后的图片数据 201 * 202
    public void setPicToView(Intent data) {
        Bundle  exreas = data.getExtras();
        if(exreas !=null){
            Bitmap  photo = exreas.getParcelable("data");
            Drawable  drawable = new BitmapDrawable(photo);

            /* 下面注释的方法是将裁剪之后的图片
		                   以Base64Coder的字符方式上 传到服务器，
		       QQ头像上传采用的方法跟这个类似 213
		    */
            mHeaderImageView.setImageBitmap(photo);
            //saveImage(data);
        }
    }

    public void saveImage(Intent data) {
        if(FileUtils.exists(Constants.IMAGE_CAPTURE_URI.getPath())){
            String  imageName = UUID.randomUUID().toString() + ".jpg";
            //file path 存文件的地址
           String path = Environment.getExternalStorageDirectory().toString() + Constants.PATH_USER_HEADER + imageName;
           FileUtils.fileCpy(Constants.IMAGE_CAPTURE_URI.getPath(), path, true);
           Bitmap  bit = BitmapFactory.decodeFile(path);
           if(bit !=null){
               mImageName = imageName;
               mHeaderImageView.setImageDrawable(new BitmapDrawable(bit));
               ImageLoader.getInstance().putBitmapIntoMemCache(path, bit);
               /*mLoginInfo = LoginApplication.getInstance().getUser();
               mLoginInfo.setAvatarUrl(path);*/
           }else{
               Toast.makeText(this, "失败", Toast.LENGTH_SHORT).show();
           }
            FileUtils.clearFileInDir(Constants.IMAGE_CAPTURE_URI.getPath());
            /*if(data == REQUEST_CODE_CAMERA){
                FileUtils.clearFileInDir(Constants.IMAGE_CAPTURE_URI.getPath());
            }*/
           // initDatas();
        }else{
            Toast.makeText(this, "失败", Toast.LENGTH_SHORT).show();
        }
    }
}
